package controllers

import (
	"bolg_admin/app/models/articleCon"
	"bolg_admin/app/models/articleInf"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
)

//CreateArticleInf 创建文章信息
func CreateArticleInf(c *gin.Context) {
	title := c.PostForm("title")
	summary := c.PostForm("summary")
	announcer, _ := c.Get("userId")
	userName := c.PostForm("userName")
	body := c.PostForm("body")

	con := articleCon.ArticleCon{
		Body: body,
	}
	conId, errCon := con.CreateCon()

	if errCon != nil {
		return
	}

	Inf := articleInf.ArticleInf{
		UserName:     userName,
		Title:        title,
		Summary:      summary,
		Announcer:    announcer.(uint),
		ArticleConId: conId,
	}

	_, err := Inf.CreateInf()
	if err != nil {
		c.JSON(400, gin.H{
			"data": gin.H{},
			"meta": gin.H{
				"msg":  "失败",
				"code": 400,
			},
		})
		return
	}

	c.JSON(200, gin.H{
		"data": gin.H{},
		"meta": gin.H{
			"msg":  "成功",
			"code": 200,
		},
	})
}

//GetArticleInf 查询文章信息
func GetArticleInf(c *gin.Context) {
	page := c.PostForm("page")
	pageSize := c.PostForm("pageSize")
	pageInt, _ := strconv.Atoi(page)
	pageSizeInt, _ := strconv.Atoi(pageSize)
	articleInfData, count := articleInf.SeArticleInf(pageInt, pageSizeInt)
	c.JSON(200, gin.H{
		"data": gin.H{
			"result": articleInfData,
			"count":  count,
		},
		"meta": gin.H{
			"msg":  "成功",
			"code": 200,
		},
	})
}

//GetArticleCon 查询文章内容
func GetArticleCon(c *gin.Context) {

	conId := c.PostForm("articleConId")

	conIdInt, _ := strconv.Atoi(conId)

	con, err := articleCon.GetArticleCon(uint64(conIdInt))

	if err != nil {
		c.JSON(400, gin.H{
			"data": gin.H{},
			"meta": gin.H{
				"msg":  "失败",
				"code": 400,
			},
		})
		return
	}

	c.JSON(200, gin.H{
		"data": gin.H{
			"body": con,
		},
		"meta": gin.H{
			"msg":  "成功",
			"code": 200,
		},
	})
}

func GetInfData(c *gin.Context) {

	conId := c.PostForm("articleConId")
	fmt.Println("conid", conId)
	conIdInt, _ := strconv.Atoi(conId)
	fmt.Println("conid", conId)
	inf, err := articleInf.GetArticleInf(uint64(conIdInt))

	if err != nil {
		c.JSON(400, gin.H{
			"data": gin.H{},
			"meta": gin.H{
				"msg":  "失败",
				"code": 400,
			},
		})
		return
	}

	c.JSON(200, gin.H{
		"data": gin.H{
			"body": inf,
		},
		"meta": gin.H{
			"msg":  "成功",
			"code": 200,
		},
	})

}
